import Router from "@koa/router";
import { z } from "zod";
import { DEFAULT_AVATAR } from "@/common/avatar";
import type { User } from "@/data/users";
import { auth, authOptional, getToken, tryGetToken } from "@/middlewares/auth";
import { getMe, login, logout } from "@/services/auth";

const router = new Router();

function maskMe(me: User) {
  return {
    id: me.id,
    username: me.username,
    avatar: me.avatar || DEFAULT_AVATAR,
  };
}

router.get("/profile", auth, async (ctx) => {
  const token = getToken(ctx);
  const me = await getMe(token);
  ctx.body = maskMe(me);
});

const LOGIN_PAYLOAD_SCHEMA = z.object({
  username: z.string().min(3).max(30),
  password: z.string().min(10).max(64),
});

router.post("/login", async (ctx) => {
  const result = LOGIN_PAYLOAD_SCHEMA.safeParse(ctx.request.body);
  if (result.error) {
    throw result.error;
  }
  const { username, password } = result.data;
  const { token, ttlSeconds, user } = await login({ username, password });
  ctx.body = maskMe(user);
  ctx.cookies.set("token", token, {
    maxAge: ttlSeconds * 1000,
    httpOnly: true,
  });
});

router.post("/logout", authOptional, (ctx) => {
  const token = tryGetToken(ctx);
  if (token) {
    logout(token);
  }
  ctx.cookies.set("token", "", { maxAge: 0, httpOnly: true });
  ctx.body = "";
});

export default router;
